import os
import json

from typing import Dict, Any
from langchain_core.messages import HumanMessage, AIMessage


class HistoryManager:
    def __init__(self, cfg: Dict[str, Any]):
        history_dir = cfg.get('history_path')
        self.max_turns = cfg.get('history_turns')
        self.path = os.path.join(history_dir, 'history.json')
        os.makedirs(history_dir, exist_ok=True)
        self._history = None

    def _load(self):
        if self._history is not None:
            return self._history
        if not os.path.isfile(self.path):
            self._history = []
            return self._history
        with open(self.path, "r", encoding="utf-8") as f:
            content = f.read().strip()
            self._history = json.loads(content) if content else []
            return self._history

    def update(self, role, content):
        if self._history is None:
            self._load()
        self._history.append({"role": role, "content": content})

        if len(self._history) > 2 * self.max_turns:
            self._history = self._history[-2 * self.max_turns :]
        with open(self.path, "w", encoding="utf-8") as f:
            json.dump(self._history, f, ensure_ascii=False, indent=2)

    def get_messages(self):
        messages = []
        for m in self._load():
            if m.get("role") == "user":
                messages.append(HumanMessage(content=m["content"]))
            elif m.get("role") == "assistant":
                messages.append(AIMessage(content=m["content"]))
        return messages
